﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using workflowMVC.Models;
using DataTool;
using DataTables;

namespace workflowMVC.Controllers
{
    
    public class AccountController : Controller
    {
        [Authorize(Roles = "Admin")]
        public ActionResult CreateStudent()
        {
            var entity = new wfdbEntities();
            List<SelectListItem> StudyClass = new List<SelectListItem>();
            foreach (var r in entity.CLASSes)
            {
                StudyClass.Add(new SelectListItem
                {
                    Value = r.Id,
                    Text = r.Id,
                });
            }
            ViewData["StudyClass"] = new SelectList(StudyClass, "Value", "Text");

            List<SelectListItem> StartYear = new List<SelectListItem>();
            foreach (var r in Enumerable.Range(2007,DateTime.Now.Year - 2007 + 1))
            {
                StartYear.Add(new SelectListItem
                {
                    Value = r.ToString(),
                    Text = r.ToString(),
                });
            }
            ViewData["StartYear"] = new SelectList(StartYear, "Value", "Text");

            List<SelectListItem> TimeLast = new List<SelectListItem>();
            foreach (var r in entity.TIMELASTs)
            {
                TimeLast.Add(new SelectListItem
                {
                    Value = r.Id.ToString(),
                    Text = r.Description,
                });
            }
            ViewData["TimeLast"] = new SelectList(TimeLast, "Value", "Text");

            List<SelectListItem> EduMode = new List<SelectListItem>();
            foreach (var r in entity.EDUMODEs)
            {
                EduMode.Add(new SelectListItem
                {
                    Value = r.Id.ToString(),
                    Text = r.Description,
                });
            }
            ViewData["EduMode"] = new SelectList(EduMode, "Value", "Text");

            return View();
        }

        [Authorize(Roles = "Admin")]
        [HttpPost]
        public ActionResult CreateStudent(StudentModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                MembershipCreateStatus createStatus;
                Membership.CreateUser(model.NumCode, "123456", model.Email, null, null, true, null, out createStatus);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    Roles.AddUserToRole(model.NumCode, "Student");
                    STUDENT s = new STUDENT();
                    s.DoB = model.DoB;
                    s.Name = model.Name;
                    s.NumCode = model.NumCode;
                    s.Address = model.Address;
                    s.Class = model.Class;
                    s.StartYear = model.StartYear;
                    s.TimeLast = model.TimeLast;
                    s.EduMode = model.EduMode;
                    Util.entity.STUDENTs.AddObject(s);
                    Util.entity.SaveChanges();
                    ViewBag.NotifyResult = "Tạo thành khoảnh thành công";
                    return View("NotifyResult");
                }
                else
                {
                    ModelState.AddModelError("", Util.ErrorCodeToString(createStatus));
                }
            }

            // If we got this far, something failed, redisplay form

            var entity = new wfdbEntities();
            List<SelectListItem> StudyClass = new List<SelectListItem>();
            foreach (var r in entity.CLASSes)
            {
                StudyClass.Add(new SelectListItem
                {
                    Value = r.Id,
                    Text = r.Id,
                });
            }
            ViewData["StudyClass"] = new SelectList(StudyClass, "Value", "Text");

            List<SelectListItem> StartYear = new List<SelectListItem>();
            foreach (var r in Enumerable.Range(2007, DateTime.Now.Year - 2007 + 1))
            {
                StartYear.Add(new SelectListItem
                {
                    Value = r.ToString(),
                    Text = r.ToString(),
                });
            }
            ViewData["StartYear"] = new SelectList(StartYear, "Value", "Text");

            List<SelectListItem> TimeLast = new List<SelectListItem>();
            foreach (var r in entity.TIMELASTs)
            {
                TimeLast.Add(new SelectListItem
                {
                    Value = r.Id.ToString(),
                    Text = r.Description,
                });
            }
            ViewData["TimeLast"] = new SelectList(TimeLast, "Value", "Text");

            List<SelectListItem> EduMode = new List<SelectListItem>();
            foreach (var r in entity.EDUMODEs)
            {
                EduMode.Add(new SelectListItem
                {
                    Value = r.Id.ToString(),
                    Text = r.Description,
                });
            }
            ViewData["EduMode"] = new SelectList(EduMode, "Value", "Text");

            return View(model);
        }

        [Authorize(Roles = "Checker,Approver,Admin")]
        public ActionResult StudentDetail(string id)
        {            
            StudentDetailModel m = new StudentDetailModel();
            wfdbEntities db = new wfdbEntities();
            var student = db.STUDENTs.Where(x => x.NumCode == id).FirstOrDefault();
            m.Address = student.Address;
            m.Class = student.Class;
            m.DoB = student.DoB.Value;
            m.EduMode = student.EDUMODE1.Description;
            m.Email = Membership.GetUser(id).Email;
            m.IsApprove = Membership.GetUser(id).IsApproved;
            m.Name = student.Name;
            m.NumCode = id;
            m.StartYear = student.StartYear.Value;
            m.TimeLast = student.TIMELAST1.Description;
            var tasks=db.TASKs.Where(x => x.NumCode == id);
            foreach (var i in tasks)
            {
                string s = i.LOGs.Where(x => x.Kind == 1).FirstOrDefault().Date
                    + " -- Loại đơn " + i.TASKKIND.Description + " -- Đang ở trạng thái " + i.TASKSTATU.Description;
                m.Logs.Add(s);
            }

            return View(m);
        }

        [Authorize(Roles = "Admin,Checker")]
        public ActionResult ListStudent()
        {
            ViewBag.datasource = Url.Action("ListStudentData");
            return View();
        }

        [Authorize(Roles = "Admin,Checker")]
        public JsonResult ListStudentData()
        {
            wfdbEntities db = new wfdbEntities();

            var data = db.STUDENTs.AsEnumerable().Select(x =>
                new ListStudentModel
                {
                    Class = x.Class,
                    Department = x.CLASS1.DEPARTMENT1.Description,
                    Name = x.Name,
                    NumCode = x.NumCode,
                    IsApproved = Membership.GetUser(x.NumCode).IsApproved,
                    Action = ""
                }
                );
            var cs = new DataTableParser<ListStudentModel>(Request, data.AsQueryable()).Parse();
            cs.aaData.ForEach(x => 
                {
                    x[5] = Util.getsTableLink(new { @class = Util.detail },
                        new { title = "Xem", href = Url.Action("StudentDetail", new { id = x[0] }) });
                    if(x[4]=="True")
                    {
                        x[4] = "Hoạt động";
                        x[5] += 
                        Util.getsTableLink(new { @class = Util.lockacc + " lock" },
                        new { title = "Khoá tài khoản", href = Url.Action("LockStudent", new { id = x[0] }) }) ;
                    }
                    else 
                    {
                        x[4] = "Đã khóa";
                        x[5] +=Util.getsTableLink(new { @class = Util.unlockacc + " unlock" },
                        new { title = "Mở khóa tài khoản", href = Url.Action("UnlockStudent", new { id = x[0] }) });
                    }                   
                        
                }
                
                );
            return Json(cs);
        }

        [Authorize(Roles = "Admin,Checker")]
        [HttpPut]
        public void LockStudent(string id)
        {
            var user = Membership.GetUser(id);
            user.IsApproved = false;
            Membership.UpdateUser(user);
        }

        [Authorize(Roles = "Admin,Checker")]
        [HttpPut]
        public void UnlockStudent(string id)
        {
            var user = Membership.GetUser(id);
            user.IsApproved = true;
            Membership.UpdateUser(user);
        }
    }
}
